<template>
  <div class="app-container">
    <!-- 头部 -->
    <div class="header">
      <h1>金料管理系统</h1>
      <!-- <p>专注于金料操作记录，支持手机端 H5 操作</p> -->
    </div>

    <div class="main-content">
      <!-- 统计卡片 -->
      <!-- 
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-number">{{ stats.balance.toFixed(3) }}</div>
          <div class="stat-label">总金料余额（克）</div>
        </div>
        <div class="stat-card">
          <div class="stat-number">{{ stats.warehouseCount }}</div>
          <div class="stat-label">仓库数量</div>
        </div>
        <div class="stat-card">
          <div class="stat-number">{{ stats.todayIn.toFixed(3) }}</div>
          <div class="stat-label">当日进料总克重（克）</div>
        </div>
        <div class="stat-card">
          <div class="stat-number">{{ stats.todayOut.toFixed(3) }}</div>
          <div class="stat-label">当日出料总克重（克）</div>
        </div>
      </div>
      -->

      <el-card shadow="never">
        <el-tabs v-model="activeTab" @tab-change="onTabChange">
          <el-tab-pane label="商家户" name="merchant">
            <div class="search-form">
              <div class="search-form-header" @click="toggleMerchantSearch">
                <span>筛选条件</span>
                <el-icon
                  class="search-toggle-icon"
                  :class="{ 'is-collapsed': !merchantSearchExpanded }"
                >
                  <ArrowDown v-if="!merchantSearchExpanded" />
                  <ArrowUp v-else />
                </el-icon>
              </div>
              <el-collapse-transition>
                <div v-show="merchantSearchExpanded">
                  <el-form :model="merchantQuery" :inline="true">
                    <el-form-item label="仓库名称">
                      <el-input
                        v-model="merchantQuery.name"
                        placeholder="请输入仓库名称"
                        clearable
                        style="width: 200px"
                      />
                    </el-form-item>
                    <el-form-item label="仓库类型">
                      <el-select
                        v-model="merchantQuery.type"
                        clearable
                        placeholder="请选择仓库类型"
                        style="width: 150px"
                        @change="onMerchantTypeChange"
                      >
                        <el-option label="公司仓" :value="1" />
                        <el-option label="团队仓" :value="2" />
                      </el-select>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="loadMerchant">搜索</el-button>
                      <el-button @click="resetMerchant">重置</el-button>
                      <el-button type="success" @click="openAddWarehouseDialog">增加账户</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-collapse-transition>
            </div>

            <!-- 调试信息 -->

            <el-table
              :data="merchantList"
              v-loading="merchantLoading"
              stripe
              @row-dblclick="openWarehouseDetail"
            >
              <el-table-column label="仓库名称" prop="name" align="center" :min-width="80" />
              <el-table-column label="仓库类型" align="center" :min-width="70">
                <template #default="{ row }">
                  <el-tag v-if="row.type === 1" type="primary">公司仓</el-tag>
                  <el-tag v-else-if="row.type === 2" type="success">团队仓</el-tag>
                  <el-tag v-else type="info">人员仓</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="余料克重" prop="balance" align="center" :min-width="80">
                <template #default="{ row }">
                  <span :class="getBalanceClass(row.balance)">
                    {{ row.balance?.toFixed(3) }} 克
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                label="负责人"
                prop="responsiblePerson"
                align="center"
                :min-width="60"
              />
              <el-table-column
                label="操作时间"
                prop="updateTime"
                align="center"
                show-overflow-tooltip
                class-name="operation-time-column"
              >
                <template #default="{ row }">
                  {{ row.updateTime ? formatToDateTime(row.updateTime) : '-' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" :min-width="100" fixed="right">
                <template #default="{ row }">
                  <div class="operation-buttons operation-buttons-vertical">
                    <el-button
                      size="small"
                      type="primary"
                      @click="openForm('buy-in', row)"
                      v-hasPermi="['gold:material-record:buy-in']"
                      >买料入料</el-button
                    >
                    <el-button
                      size="small"
                      type="success"
                      @click="openForm('sales-return', row)"
                      v-hasPermi="['gold:material-record:sales-return']"
                      >销售回料</el-button
                    >
                    <el-button
                      size="small"
                      type="warning"
                      @click="openForm('outbound', row)"
                      v-hasPermi="['gold:material-record:reduce']"
                      >采料出料</el-button
                    >
                    <el-button
                      size="small"
                      type="info"
                      @click="openForm('transfer', row)"
                      v-hasPermi="['gold:material-transfer:transfer']"
                      >调拨</el-button
                    >
                    <el-button
                      size="small"
                      type="success"
                      @click="openForm('dispatch', row)"
                      v-hasPermi="['gold:material-transfer:dispatch']"
                      >派发</el-button
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination-container">
              <el-pagination
                :current-page="merchantQuery.pageNo"
                :page-size="merchantQuery.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="merchantTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleMerchantSizeChange"
                @current-change="handleMerchantCurrentChange"
              />
            </div>
          </el-tab-pane>

          <el-tab-pane label="销售户" name="sales">
            <div class="search-form">
              <div class="search-form-header" @click="toggleSalesSearch">
                <span>筛选条件</span>
                <el-icon
                  class="search-toggle-icon"
                  :class="{ 'is-collapsed': !salesSearchExpanded }"
                >
                  <ArrowDown v-if="!salesSearchExpanded" />
                  <ArrowUp v-else />
                </el-icon>
              </div>
              <el-collapse-transition>
                <div v-show="salesSearchExpanded">
                  <el-form :model="salesQuery" :inline="true">
                    <el-form-item label="仓库名称">
                      <el-input
                        v-model="salesQuery.name"
                        placeholder="请输入仓库名称"
                        clearable
                        style="width: 200px"
                      />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="loadSales">搜索</el-button>
                      <el-button @click="resetSales">重置</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-collapse-transition>
            </div>

            <el-table
              :data="salesList"
              v-loading="salesLoading"
              stripe
              @row-dblclick="openWarehouseDetail"
            >
              <el-table-column label="仓库名称" prop="name" align="center" :min-width="80" />
              <el-table-column label="仓库类型" align="center" :min-width="70">
                <template #default="{ row }">
                  <el-tag v-if="row.type === 1" type="primary">公司仓</el-tag>
                  <el-tag v-else-if="row.type === 2" type="success">团队仓</el-tag>
                  <el-tag v-else type="info">人员仓</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="余料克重" prop="balance" align="center" :min-width="80">
                <template #default="{ row }">
                  <span :class="getBalanceClass(row.balance)"
                    >{{ row.balance?.toFixed(3) }} 克</span
                  >
                </template>
              </el-table-column>
              <el-table-column
                label="负责人"
                prop="responsiblePerson"
                align="center"
                :min-width="60"
              />
              <el-table-column
                label="操作时间"
                prop="updateTime"
                align="center"
                show-overflow-tooltip
                class-name="operation-time-column"
              >
                <template #default="{ row }">
                  {{ row.updateTime ? formatToDateTime(row.updateTime) : '-' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" :min-width="100" fixed="right">
                <template #default="{ row }">
                  <div class="operation-buttons-vertical">
                    <el-button
                      size="small"
                      type="primary"
                      @click="openForm('buy-in', row)"
                      v-hasPermi="['gold:material-record:buy-in']"
                      >买料入料</el-button
                    >
                    <el-button
                      size="small"
                      type="success"
                      @click="openForm('sales-return', row)"
                      v-hasPermi="['gold:material-record:sales-return']"
                      >销售回料</el-button
                    >
                    <el-button
                      size="small"
                      type="warning"
                      @click="openForm('outbound', row)"
                      v-hasPermi="['gold:material-record:reduce']"
                      >采料出料</el-button
                    >
                    <el-button
                      size="small"
                      @click="openForm('return', row)"
                      v-hasPermi="['gold:material-record:return']"
                      >还料</el-button
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination-container">
              <el-pagination
                :current-page="salesQuery.pageNo"
                :page-size="salesQuery.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="salesTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSalesSizeChange"
                @current-change="handleSalesCurrentChange"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 操作对话框 -->
    <el-dialog
      v-model="operationDialogVisible"
      :title="operationTitle"
      width="500px"
      class="operation-dialog"
      :style="isMobile ? 'width: 90%' : ''"
    >
      <el-form :model="operationForm" label-width="100px">
        <!-- 买料入料操作表单 -->
        <template v-if="operationType === 'buy-in'">
          <el-form-item label="仓库" required>
            <el-input :value="currentWarehouse?.name" disabled />
          </el-form-item>

          <el-form-item label="操作克重" required>
            <el-input-number
              v-model="operationForm.weight"
              :min="0"
              :precision="3"
              placeholder="请输入操作克重"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="期初克重">
            <el-input-number
              v-model="operationForm.initialWeight"
              :min="0"
              :precision="3"
              disabled
              style="width: 100%"
            />
          </el-form-item>

          <!-- <el-form-item label="关联订单号">
            <el-input
              v-model="operationForm.relatedOrderNo"
              placeholder="请选择关联订单号"
              readonly
              style="width: calc(100% - 80px)"
            />
            <el-button
              type="primary"
              @click="openOrderSelection('purchase')"
              style="margin-left: 8px"
            >
              选择
            </el-button>
          </el-form-item> -->

          <el-form-item label="操作人" required>
            <el-input v-model="operationForm.creator" placeholder="请输入操作人" />
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="operationForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
            />
          </el-form-item>
        </template>

        <!-- 销售回料操作表单 -->
        <template v-if="operationType === 'sales-return'">
          <el-form-item label="仓库" required>
            <el-input :value="currentWarehouse?.name" disabled />
          </el-form-item>

          <el-form-item label="操作克重" required>
            <el-input-number
              v-model="operationForm.weight"
              :min="0"
              :precision="3"
              placeholder="请输入操作克重"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="期初克重">
            <el-input-number
              v-model="operationForm.initialWeight"
              :min="0"
              :precision="3"
              disabled
              style="width: 100%"
            />
          </el-form-item>

          <!-- <el-form-item label="关联订单号">
            <el-input
              v-model="operationForm.relatedOrderNo"
              placeholder="请选择关联订单号"
              readonly
              style="width: calc(100% - 80px)"
            />
            <el-button
              type="primary"
              @click="openOrderSelection('purchase')"
              style="margin-left: 8px"
            >
              选择
            </el-button>
          </el-form-item> -->

          <el-form-item label="操作人" required>
            <el-input v-model="operationForm.creator" placeholder="请输入操作人" />
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="operationForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
            />
          </el-form-item>
        </template>

        <!-- 采料出料操作表单 -->
        <template v-if="operationType === 'outbound'">
          <el-form-item label="仓库" required>
            <el-input :value="currentWarehouse?.name" disabled />
          </el-form-item>

          <el-form-item label="操作克重" required>
            <el-input-number
              v-model="operationForm.weight"
              :min="0"
              :precision="3"
              placeholder="请输入操作克重"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="期初克重">
            <el-input-number
              v-model="operationForm.initialWeight"
              :min="0"
              :precision="3"
              disabled
              style="width: 100%"
            />
          </el-form-item>

          <!-- <el-form-item label="关联订单号">
            <el-input
              v-model="operationForm.relatedOrderNo"
              placeholder="请选择关联订单号"
              readonly
              style="width: calc(100% - 80px)"
            />
            <el-button type="primary" @click="openOrderSelection('sales')" style="margin-left: 8px">
              选择
            </el-button>
          </el-form-item> -->

          <el-form-item label="操作人" required>
            <el-input v-model="operationForm.creator" placeholder="请输入操作人" />
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="operationForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
            />
          </el-form-item>
        </template>

        <!-- 调拨操作表单 -->
        <template v-if="operationType === 'transfer'">
          <el-form-item label="调出仓库" required>
            <el-input :value="currentWarehouse?.name" disabled />
          </el-form-item>

          <el-form-item label="调入仓库" required>
            <el-select
              v-model="operationForm.toWarehouseId"
              placeholder="请选择调入仓库"
              style="width: 100%"
            >
              <el-option
                v-for="warehouse in warehouseList"
                :key="warehouse.id"
                :label="warehouse.name"
                :value="warehouse.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="调拨克重" required>
            <el-input-number
              v-model="operationForm.transferWeight"
              :min="0"
              :precision="3"
              placeholder="请输入调拨克重"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="调拨原因">
            <el-input v-model="operationForm.transferReason" placeholder="请输入调拨原因" />
          </el-form-item>

          <el-form-item label="操作人" required>
            <el-input v-model="operationForm.creator" placeholder="请输入操作人" />
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="operationForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
            />
          </el-form-item>
        </template>

        <!-- 派发操作表单 -->
        <template v-if="operationType === 'dispatch'">
          <el-form-item label="派发仓库" required>
            <el-input :value="currentWarehouse?.name" disabled />
          </el-form-item>

          <el-form-item label="接收仓库" required>
            <el-select
              v-model="operationForm.toWarehouseId"
              placeholder="请选择接收仓库"
              style="width: 100%"
            >
              <el-option
                v-for="warehouse in warehouseList"
                :key="warehouse.id"
                :label="warehouse.name"
                :value="warehouse.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="派发克重" required>
            <el-input-number
              v-model="operationForm.dispatchWeight"
              :min="0.001"
              :precision="3"
              placeholder="请输入派发克重"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="派发原因">
            <el-input v-model="operationForm.dispatchReason" placeholder="请输入派发原因" />
          </el-form-item>

          <el-form-item label="操作人" required>
            <el-input v-model="operationForm.creator" placeholder="请输入操作人" />
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="operationForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
            />
          </el-form-item>
        </template>

        <!-- 还料操作表单 -->
        <template v-if="operationType === 'return'">
          <el-form-item label="还料出料仓" required>
            <el-input :value="currentWarehouse?.name" disabled />
          </el-form-item>

          <el-form-item label="还料入料仓" required>
            <el-input :value="returnOutboundWarehouse?.name || '正在查询...'" disabled />
          </el-form-item>

          <el-form-item label="还料克重" required>
            <el-input-number
              v-model="operationForm.returnWeight"
              :min="0"
              :precision="3"
              placeholder="请输入还料克重"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="还料原因">
            <el-input v-model="operationForm.returnReason" placeholder="请输入还料原因" />
          </el-form-item>

          <el-form-item label="操作人" required>
            <el-input v-model="operationForm.creator" placeholder="请输入操作人" />
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="operationForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
            />
          </el-form-item>
        </template>

        <!-- 通用字段 -->

        <el-form-item label="附件">
          <el-upload
            class="upload-demo"
            drag
            :action="uploadUrl"
            :http-request="httpRequest"
            :file-list="uploadedFiles"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            @remove="handleUploadRemove"
            accept=".jpg,.jpeg,.png,.pdf"
            :limit="1"
            :before-upload="beforeUpload"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text"> 将文件拖到此处，或<em>点击上传</em> </div>
            <template #tip>
              <div class="el-upload__tip"> 支持jpg/png/pdf文件，且不超过10MB </div>
            </template>
          </el-upload>

          <!-- 已上传文件预览 -->
          <div v-if="operationForm.attachmentUrl" class="attachment-preview">
            <div class="attachment-item">
              <el-icon class="attachment-icon"><UploadFilled /></el-icon>
              <span class="attachment-name">{{ getFileName(operationForm.attachmentUrl) }}</span>
              <el-button type="danger" size="small" link @click="removeAttachment">
                删除
              </el-button>
              <el-button type="primary" size="small" link @click="previewAttachment">
                预览
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="operationDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitOperation" :loading="operationSubmitting"
          >确定</el-button
        >
      </template>
    </el-dialog>

    <!-- 仓库详情弹窗 -->
    <el-dialog
      v-model="warehouseDetailVisible"
      title="仓库详情"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="selectedWarehouse" class="warehouse-detail">
        <!-- 仓库基本信息 -->
        <div class="warehouse-info">
          <h3>{{ selectedWarehouse.name }} - 详细信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">仓库名称：</span>
              <span class="value">{{ selectedWarehouse.name }}</span>
            </div>
            <div class="info-item">
              <span class="label">仓库类型：</span>
              <el-tag v-if="selectedWarehouse.type === 1" type="primary">公司仓</el-tag>
              <el-tag v-else-if="selectedWarehouse.type === 2" type="success">团队仓</el-tag>
              <el-tag v-else type="info">人员仓</el-tag>
            </div>
            <div class="info-item">
              <span class="label">余料克重：</span>
              <span class="value">{{ selectedWarehouse.balance?.toFixed(3) }} 克</span>
            </div>
            <div class="info-item">
              <span class="label">负责人：</span>
              <span class="value">{{ selectedWarehouse.responsiblePerson || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">操作时间：</span>
              <span class="value">{{
                selectedWarehouse.updateTime ? formatToDateTime(selectedWarehouse.updateTime) : '-'
              }}</span>
            </div>
          </div>
        </div>

        <!-- 操作记录统计 -->
        <div class="record-stats">
          <div class="stat-card">
            <div class="stat-number green">{{ recordStats.todayIn?.toFixed(3) || '0.000' }}克</div>
            <div class="stat-label">今日总入克重</div>
          </div>
          <div class="stat-card">
            <div class="stat-number red">{{ recordStats.todayOut?.toFixed(3) || '0.000' }}克</div>
            <div class="stat-label">今日总出克重</div>
          </div>
          <div class="stat-card">
            <div class="stat-number green">{{ recordStats.balance?.toFixed(3) || '0.000' }}克</div>
            <div class="stat-label">余料克重</div>
          </div>
        </div>

        <!-- 操作记录列表 -->
        <div class="record-list">
          <h4>操作记录</h4>
          <div v-loading="recordLoading" class="records-container">
            <div v-for="record in recordList" :key="record.id" class="record-item">
              <div class="record-header">
                <span class="record-time">{{ formatToDateTime(record.createTime) }}</span>
              </div>
              <div class="record-content">
                <div class="record-left">
                  <div class="record-type">
                    <el-tag :type="getRecordTagType(record.operationSubtype)" size="small">
                      {{ getRecordTypeText(record.operationSubtype) }}
                    </el-tag>
                    <span class="record-subtype">{{
                      getRecordSubtypeText(record.operationSubtype)
                    }}</span>
                  </div>
                  <div class="record-details">
                    <div class="detail-item">
                      <span class="detail-label">操作人：</span>
                      <span class="detail-value">{{ record.operatorName || '系统' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">期初克重：</span>
                      <span class="detail-value">{{
                        record.initialWeight ? record.initialWeight.toFixed(3) + '克' : '0.000克'
                      }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">操作克重：</span>
                      <span
                        class="detail-value"
                        :class="getWeightClass(record.operationWeight, record.operationType)"
                      >
                        {{ getFormattedWeight(record.operationWeight, record.operationType) }}
                      </span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">余料克重：</span>
                      <span class="detail-value">{{
                        record.finalWeight ? record.finalWeight.toFixed(3) + '克' : '0.000克'
                      }}</span>
                    </div>
                    <div class="detail-item" v-if="record.relatedBusinessNo">
                      <span class="detail-label">关联业务单号：</span>
                      <span class="detail-value">{{ record.relatedBusinessNo }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">备注：</span>
                      <span class="detail-value">{{ record.remark || '空' }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">附件：</span>
                      <span class="detail-value">
                        <span v-if="record.attachmentUrl" class="attachment-link">
                          <a :href="record.attachmentUrl" target="_blank" class="detail-link"
                            >查看附件</a
                          >
                        </span>
                        <span v-else class="attachment-empty">空</span>
                      </span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">仓库：</span>
                      <span class="detail-value">{{ selectedWarehouse.name }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-if="!recordLoading && recordList.length === 0" class="empty-state">
              <el-empty description="暂无操作记录" />
            </div>
          </div>

          <!-- 分页 -->
          <div class="record-pagination">
            <el-pagination
              :current-page="recordQuery.pageNo"
              :page-size="recordQuery.pageSize"
              :page-sizes="[10, 20, 50]"
              :total="recordTotal"
              layout="total, sizes, prev, pager, next"
              @size-change="handleRecordSizeChange"
              @current-change="handleRecordCurrentChange"
            />
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 新增仓库弹窗 -->
    <el-dialog v-model="addWarehouseDialogVisible" title="新增仓库" width="500px">
      <el-form
        :model="warehouseForm"
        :rules="warehouseRules"
        ref="warehouseFormRef"
        label-width="100px"
      >
        <el-form-item label="仓库编码" prop="code">
          <el-input v-model="warehouseForm.code" placeholder="请输入仓库编码" />
        </el-form-item>

        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="warehouseForm.name" placeholder="请输入仓库名称" />
        </el-form-item>

        <el-form-item label="仓库类型" prop="type">
          <el-select
            v-model="warehouseForm.type"
            placeholder="请选择仓库类型"
            style="width: 100%"
            @change="onWarehouseTypeChange"
          >
            <el-option label="公司仓" :value="1" />
            <el-option label="团队仓" :value="2" />
            <el-option label="人员仓" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="绑定团队仓" prop="teamWarehouseId" v-if="warehouseForm.type === 3">
          <el-select
            v-model="warehouseForm.teamWarehouseId"
            placeholder="请选择团队仓"
            style="width: 100%"
            filterable
            clearable
          >
            <el-option
              v-for="warehouse in teamWarehouseList"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="负责人" prop="responsiblePersonId">
          <el-select
            v-model="warehouseForm.responsiblePersonId"
            placeholder="请选择负责人"
            style="width: 100%"
            filterable
            clearable
            @change="onResponsiblePersonChange"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.nickname || user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="warehouseForm.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addWarehouseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitWarehouse" :loading="warehouseSubmitting"
          >确定</el-button
        >
      </template>
    </el-dialog>

    <!-- 订单选择弹窗 -->
    <el-dialog
      v-model="orderSelectionDialogVisible"
      :title="
        orderSelectionType === 'purchase'
          ? '选择采购订单 (仅展示可入库)'
          : '选择销售订单 (仅展示可出库)'
      "
      width="1000px"
    >
      <!-- 搜索条件 -->
      <el-form :model="orderQuery" inline>
        <el-form-item label="订单单号">
          <el-input
            v-model="orderQuery.orderNo"
            placeholder="请输入订单单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="产品">
          <el-select
            v-model="orderQuery.product"
            placeholder="请选择产品"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="product in productList"
              :key="product.id"
              :label="product.name"
              :value="product.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单时间">
          <el-date-picker
            v-model="orderQuery.startDate"
            type="date"
            placeholder="开始日期"
            style="width: 150px"
          />
          <span style="margin: 0 8px">-</span>
          <el-date-picker
            v-model="orderQuery.endDate"
            type="date"
            placeholder="结束日期"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchOrders">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetOrderQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 订单列表 -->
      <el-table
        :data="orderList"
        v-loading="orderLoading"
        @selection-change="handleOrderSelection"
        style="margin-top: 20px"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单单号" width="150" />
        <el-table-column prop="supplier" label="供应商" v-if="orderSelectionType === 'purchase'" />
        <el-table-column prop="customer" label="客户" v-if="orderSelectionType === 'sales'" />
        <el-table-column prop="productInfo" label="产品信息" width="120" />
        <el-table-column prop="orderTime" label="订单时间" width="120" />
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="totalQuantity" label="总数量" width="100" />
        <el-table-column
          prop="inboundQuantity"
          label="入库数量"
          v-if="orderSelectionType === 'purchase'"
          width="100"
        />
        <el-table-column
          prop="outboundQuantity"
          label="出库数量"
          v-if="orderSelectionType === 'sales'"
          width="100"
        />
        <el-table-column prop="totalAmount" label="金额合计" width="120" />
        <el-table-column prop="taxAmount" label="含税金额" width="120" />
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right">
        <el-pagination
          v-model:current-page="orderQuery.pageNo"
          v-model:page-size="orderQuery.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="orderTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleOrderSizeChange"
          @current-change="handleOrderCurrentChange"
        />
      </div>

      <template #footer>
        <el-button @click="orderSelectionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmOrderSelection">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 用于路由缓存（keep-alive）与菜单"组件名称"一致
defineOptions({ name: 'Warehouse' })
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
import { Search, Refresh, UploadFilled, ArrowDown, ArrowUp } from '@element-plus/icons-vue'
// mark icons as referenced so eslint doesn't flag as unused (used in template)
void [Search, Refresh, UploadFilled]
import { PurchaseOrderApi } from '@/api/erp/purchase/order'
import { SaleOrderApi } from '@/api/erp/sale/order'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
// 临时解决方案：直接定义格式化函数
const formatToDateTime = (date?: any) => {
  if (!date) return '-'
  const d = new Date(date)
  return d
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}

// 使用项目现成的上传组件
const { uploadUrl, httpRequest } = useUpload()
console.log('上传URL:', uploadUrl)
import {
  getWarehousePage,
  getTransferWarehouseOptions,
  getOperationRecordPage,
  getOperationStats,
  getGlobalStats,
  createBuyIn,
  createSalesReturn,
  createOutbound,
  createTransfer,
  createDispatch,
  createReturn,
  createWarehouse
} from '../../../api/system/Warehouse'
import { GoldWarehouseApi, GoldWarehouseVO } from '@/api/gold/warehouse'
import { useUpload } from '@/components/UploadFile/src/useUpload'
import { getSimpleUserList } from '@/api/system/user'
import type { UserVO } from '@/api/system/user'

type TabName = 'merchant' | 'sales'

interface GlobalStats {
  todayIn: number
  todayOut: number
  balance: number
  warehouseCount: number
}

const activeTab = ref<TabName>('merchant')

// 移动端检测
const isMobile = ref(window.innerWidth <= 768)

// 筛选折叠状态
const merchantSearchExpanded = ref(false)
const salesSearchExpanded = ref(false)

// 新增仓库相关
const addWarehouseDialogVisible = ref(false)
const warehouseSubmitting = ref(false)
const warehouseFormRef = ref()

const warehouseForm = reactive({
  code: '',
  name: '',
  type: 1, // 默认公司仓
  teamWarehouseId: undefined as number | undefined,
  userId: undefined as number | undefined,
  responsiblePerson: '', // 负责人名称（显示用）
  responsiblePersonId: undefined as number | undefined, // 负责人ID（传给后端）
  status: 1 // 默认启用
})

const warehouseRules = {
  code: [
    { required: true, message: '请输入仓库编码', trigger: 'blur' },
    { min: 2, max: 50, message: '仓库编码长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' },
    { min: 2, max: 100, message: '仓库名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  type: [{ required: true, message: '请选择仓库类型', trigger: 'change' }],
  teamWarehouseId: [
    {
      required: true,
      message: '请选择团队仓',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (warehouseForm.type === 3 && !value) {
          callback(new Error('请选择团队仓'))
        } else {
          callback()
        }
      }
    }
  ],
  responsiblePersonId: [{ required: true, message: '请选择负责人', trigger: 'change' }]
}

// 上传工具已内联定义

const merchantQuery = reactive({
  pageNo: 1,
  pageSize: 10,
  name: '',
  type: null as number | null,
  types: [1, 2] as number[]
})
const salesQuery = reactive({
  pageNo: 1,
  pageSize: 10,
  name: '',
  type: null as number | null,
  types: [3] as number[]
})

const merchantLoading = ref(false)
const salesLoading = ref(false)
const merchantList = ref<any[]>([])
const salesList = ref<any[]>([])
const merchantTotal = ref(0)
const salesTotal = ref(0)
const teamWarehouseList = ref<GoldWarehouseVO[]>([]) // 团队仓库列表
const userList = ref<UserVO[]>([]) // 用户列表

const stats = reactive<GlobalStats>({ todayIn: 0, todayOut: 0, balance: 0, warehouseCount: 0 })

// 加载全局统计数据
async function loadGlobalStats() {
  try {
    console.log('加载全局统计数据')
    const result = (await getGlobalStats()) as any

    console.log('=== 全局统计API响应 ===')
    console.log('result:', result)
    console.log('result.data:', result?.data)

    // 处理CommonResult响应格式
    let statsData: any = null
    if (result && result.data) {
      statsData = result.data
    } else if (result && result.code === 0) {
      statsData = result
    } else if (result) {
      statsData = result
    }

    console.log('解析后的全局统计数据:', statsData)

    if (statsData) {
      stats.todayIn = statsData.todayInTotal || 0
      stats.todayOut = statsData.todayOutTotal || 0
      stats.balance = statsData.totalBalance || 0
      stats.warehouseCount = statsData.warehouseCount || 0
      console.log('设置后的全局stats:', stats)
    } else {
      console.log('全局统计API响应数据格式不正确:', result)
    }
  } catch (error) {
    console.error('加载全局统计失败:', error)
  }
}

// 仓库详情相关数据
const warehouseDetailVisible = ref(false)
const selectedWarehouse = ref<any>(null)
const recordList = ref<any[]>([])
const recordTotal = ref(0)
const recordLoading = ref(false)
const recordStats = reactive<{ todayIn: number; todayOut: number; balance: number }>({
  todayIn: 0,
  todayOut: 0,
  balance: 0
})
const recordQuery = reactive({
  pageNo: 1,
  pageSize: 10,
  warehouseId: null as number | null
})

function onMerchantTypeChange(value: number | null) {
  console.log('商家户仓库类型变更:', value)
  if (value !== null) {
    // 用户选择了具体类型，清空types数组，只使用单个type
    merchantQuery.types = []
  } else {
    // 用户清空了选择，恢复默认的types数组
    merchantQuery.types = [1, 2]
  }
}

// 销售户不再使用仓库类型筛选，此函数已移除

function getBalanceClass(balance?: number) {
  if (!balance && balance !== 0) return 'balance-low'
  if (balance >= 100) return 'balance-high'
  if (balance >= 50) return 'balance-medium'
  return 'balance-low'
}

function onTabChange() {
  console.log('切换页签到:', activeTab.value)
  if (activeTab.value === 'merchant') {
    // 商家户：显示公司仓和团队仓
    merchantQuery.name = ''
    merchantQuery.type = null
    merchantQuery.types = [1, 2] // 公司仓和团队仓
    merchantQuery.pageNo = 1
    loadMerchant()
  } else {
    // 销售户：显示人员仓
    salesQuery.name = ''
    salesQuery.type = null
    salesQuery.types = [3] // 人员仓
    salesQuery.pageNo = 1
    loadSales()
  }
}

// 切换筛选折叠状态
function toggleMerchantSearch() {
  merchantSearchExpanded.value = !merchantSearchExpanded.value
}

function toggleSalesSearch() {
  salesSearchExpanded.value = !salesSearchExpanded.value
}

async function loadMerchant() {
  merchantLoading.value = true
  try {
    console.log('开始加载商家户数据...', merchantQuery)
    console.log('发送的请求参数:', JSON.stringify(merchantQuery, null, 2))
    const pageRes = (await getWarehousePage(merchantQuery)) as any
    console.log('完整API响应:', JSON.stringify(pageRes, null, 2))

    // 尝试多种数据路径
    let list = []
    let total = 0

    if (pageRes) {
      if (pageRes.data && pageRes.data.list) {
        list = pageRes.data.list
        total = pageRes.data.total || 0
        console.log('从 pageRes.data 获取数据')
      } else if (pageRes.list) {
        list = pageRes.list
        total = pageRes.total || 0
        console.log('从 pageRes 直接获取数据')
      } else {
        console.log('未找到数据，完整响应:', pageRes)
      }
    }

    merchantList.value = list
    merchantTotal.value = total

    console.log('最终设置的数据:', {
      listLength: merchantList.value.length,
      total: merchantTotal.value,
      firstItem: merchantList.value[0],
      rawList: list
    })
  } catch (err) {
    console.error('加载商家户数据失败:', err)
    merchantList.value = []
    merchantTotal.value = 0
  } finally {
    merchantLoading.value = false
  }
}

async function loadSales() {
  salesLoading.value = true
  try {
    console.log('开始加载销售户数据...', salesQuery)
    console.log('发送的请求参数:', JSON.stringify(salesQuery, null, 2))
    // 销售户也使用同一个接口，但传递userRole='sales'
    const res = (await getWarehousePage(salesQuery)) as any
    console.log('销售户API响应:', JSON.stringify(res, null, 2))

    // 尝试多种数据路径
    let list = []
    let total = 0

    if (res) {
      if (res.data && res.data.list) {
        list = res.data.list
        total = res.data.total || 0
        console.log('从 res.data 获取数据')
      } else if (res.list) {
        list = res.list
        total = res.total || 0
        console.log('从 res 直接获取数据')
      } else {
        console.log('未找到数据，完整响应:', res)
      }
    }

    salesList.value = list
    salesTotal.value = total

    console.log('销售户最终设置的数据:', {
      listLength: salesList.value.length,
      total: salesTotal.value,
      firstItem: salesList.value[0],
      rawList: list
    })

    // 检查teamWarehouseId字段
    if (salesList.value.length > 0) {
      console.log('销售户数据中的teamWarehouseId字段检查:')
      salesList.value.forEach((item, index) => {
        console.log(`第${index + 1}项:`, {
          id: item.id,
          name: item.name,
          type: item.type,
          teamWarehouseId: item.teamWarehouseId,
          hasTeamWarehouseId: 'teamWarehouseId' in item
        })
      })
    }
  } catch (err) {
    console.error('加载销售户数据失败:', err)
    salesList.value = []
    salesTotal.value = 0
  } finally {
    salesLoading.value = false
  }
}

// 操作表单相关状态
const operationDialogVisible = ref(false)
const operationType = ref('')
const operationTitle = ref('')
const currentWarehouse = ref<any>(null)
const operationSubmitting = ref(false) // 操作提交状态
const operationForm = ref({
  warehouseId: 0,
  weight: 0, // 操作克重
  initialWeight: 0,
  operationSubtype: 1, // 操作子类型：1-销售回料，2-买料入料，3-调拨入料，4-派发入料，5-收货给料，6-调拨出料，7-派发出料，8-采购出料
  creator: '', // 操作人
  remark: '', // 备注
  attachmentUrl: '',
  // 关联订单号
  relatedOrderNo: '', // 关联订单号
  relatedOrderId: null as number | null, // 关联订单ID
  // 调拨相关
  fromWarehouseId: null as number | null,
  toWarehouseId: null as number | null,
  transferWeight: 0,
  transferReason: '',
  transferType: 0,
  // 派发相关
  operatorId: 0,
  dispatchWeight: 0,
  dispatchReason: '',
  // 还料相关
  returnWeight: 0,
  returnReason: ''
})

// 上传文件列表
const uploadedFiles = ref<any[]>([])

// 订单选择弹窗相关状态
const orderSelectionDialogVisible = ref(false)
const orderSelectionType = ref('') // 'purchase' 采购订单, 'sales' 销售订单
const orderList = ref<any[]>([])
const selectedOrder = ref<any>(null)
const orderQuery = ref({
  orderNo: '',
  product: '',
  startDate: '',
  endDate: '',
  pageNo: 1,
  pageSize: 10
})
const orderLoading = ref(false)
const orderTotal = ref(0)
const productList = ref<ProductVO[]>([]) // 产品列表

// 下拉选项数据
const warehouseList = ref<any[]>([])
const personalWarehouseList = ref<any[]>([]) // 个人仓列表
const returnOutboundWarehouse = ref<any>(null) // 还料出料仓（根据teamWarehouseId查询）

function resetOperationForm() {
  operationForm.value = {
    warehouseId: 0,
    weight: 0, // 操作克重
    initialWeight: 0,
    operationSubtype: 1, // 操作子类型：1-销售回料，2-买料入料，3-调拨入料，4-派发入料，5-收货给料，6-调拨出料，7-派发出料，8-采购出料
    creator: '', // 操作人
    remark: '', // 备注
    attachmentUrl: '',
    // 关联订单号
    relatedOrderNo: '', // 关联订单号
    relatedOrderId: null as number | null, // 关联订单ID
    // 调拨相关
    fromWarehouseId: null as number | null,
    toWarehouseId: null as number | null,
    transferWeight: 0,
    transferReason: '',
    transferType: 0,
    // 派发相关
    operatorId: 0,
    dispatchWeight: 0,
    dispatchReason: '',
    // 还料相关
    returnWeight: 0,
    returnReason: ''
  }
  uploadedFiles.value = []
}

async function openForm(type: string, row: any) {
  console.log('打开操作表单:', type, row)
  currentWarehouse.value = row
  operationType.value = type
  resetOperationForm()

  // 设置操作标题
  const typeMap = {
    'buy-in': '买料入料操作',
    'sales-return': '销售回料操作',
    outbound: '采料出料操作',
    transfer: '调拨操作',
    dispatch: '派发操作',
    return: '还料操作'
  }
  operationTitle.value = typeMap[type] || '操作'

  // 根据操作类型设置初始值
  switch (type) {
    case 'buy-in':
      operationForm.value.warehouseId = row.id
      operationForm.value.initialWeight = row.balance || 0
      operationForm.value.operationSubtype = 2 // 买料入料
      break
    case 'sales-return':
      operationForm.value.warehouseId = row.id
      operationForm.value.initialWeight = row.balance || 0
      operationForm.value.operationSubtype = 1 // 销售回料
      break
    case 'outbound':
      operationForm.value.warehouseId = row.id
      operationForm.value.initialWeight = row.balance || 0
      operationForm.value.operationSubtype = 8 // 采购出料
      break
    case 'transfer':
      operationForm.value.fromWarehouseId = row.id
      operationForm.value.toWarehouseId = null // 重置调入仓库选择
      break
    case 'dispatch':
      operationForm.value.fromWarehouseId = row.id
      operationForm.value.toWarehouseId = null // 重置接收仓库选择
      break
    case 'return':
      // 还料操作：根据当前仓库的teamWarehouseId查询对应的个人仓作为出料仓
      operationForm.value.toWarehouseId = row.id // 还料入料仓（当前仓库）
      operationForm.value.transferType = 3 // 还料操作

      // 查询还料出料仓（个人仓）
      if (row.teamWarehouseId) {
        console.log(
          '开始查询还料出料仓，teamWarehouseId:',
          row.teamWarehouseId,
          '类型:',
          typeof row.teamWarehouseId
        )
        try {
          const personalWarehouses = await GoldWarehouseApi.getPersonalWarehousesByTeamId(
            row.teamWarehouseId
          )
          console.log('接口返回数据:', personalWarehouses)
          if (personalWarehouses && personalWarehouses.length > 0) {
            // 取第一个个人仓作为出料仓
            returnOutboundWarehouse.value = personalWarehouses[0]
            operationForm.value.fromWarehouseId = personalWarehouses[0].id
            console.log('查询到还料出料仓:', personalWarehouses[0])
          } else {
            console.warn('未找到对应的个人仓')
            returnOutboundWarehouse.value = null
            operationForm.value.fromWarehouseId = null
          }
        } catch (error) {
          console.error('查询还料出料仓失败:', error)
          ElMessage.error('查询还料出料仓失败: ' + ((error as any)?.message || '未知错误'))
          returnOutboundWarehouse.value = null
          operationForm.value.fromWarehouseId = null
        }
      } else {
        console.warn('当前仓库没有teamWarehouseId:', row)
        ElMessage.warning('当前仓库没有绑定团队仓，无法进行还料操作')
        returnOutboundWarehouse.value = null
        operationForm.value.fromWarehouseId = null
      }
      break
  }

  // 加载下拉选项数据
  await loadSelectOptions()

  operationDialogVisible.value = true
}

async function loadSelectOptions() {
  try {
    console.log('加载下拉选项数据...')

    // 根据操作类型加载不同的选项
    if (operationType.value === 'transfer') {
      // 调拨需要加载仓库列表（排除当前仓库，查询公司仓和团队仓）
      const excludeId = currentWarehouse.value?.id
      console.log('查询调拨仓库选项，排除仓库ID:', excludeId)
      warehouseList.value = await getTransferWarehouseOptions(excludeId, [1, 2]) // 公司仓和团队仓
      console.log('调拨仓库选项:', warehouseList.value)
    } else if (operationType.value === 'dispatch') {
      // 派发需要加载个人仓列表，使用新的团队仓库接口
      const currentWarehouseId = currentWarehouse.value?.id
      console.log('查询派发仓库选项，当前仓库ID:', currentWarehouseId)

      try {
        if (!currentWarehouseId) {
          console.warn('当前仓库没有ID，无法加载派发仓库列表')
          warehouseList.value = []
        } else {
          // 调用接口，传递当前仓库的id
          warehouseList.value = await GoldWarehouseApi.getWarehousesByTeams(currentWarehouseId)

          // 排除当前仓库
          if (warehouseList.value) {
            warehouseList.value = warehouseList.value.filter((wh) => wh.id !== currentWarehouseId)
          }
        }

        console.log('派发仓库选项:', warehouseList.value)
        console.log('派发仓库选项数量:', warehouseList.value?.length || 0)
      } catch (err) {
        console.warn('加载派发仓库列表失败:', err)
        warehouseList.value = [] // 设置为空数组，不报错
      }
    } else if (operationType.value === 'return') {
      // 还料操作的出料仓是固定的，不需要加载个人仓列表
      console.log('还料操作：出料仓已固定，无需加载个人仓列表')
    }
  } catch (error) {
    console.error('加载选项数据失败:', error)
  }
}

// 文件上传前验证
function beforeUpload(file: any) {
  const isJPG =
    file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'application/pdf'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isJPG) {
    ElMessage.error('只能上传 JPG/PNG/PDF 格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
    return false
  }
  return true
}

function handleUploadSuccess(response: any, file: any) {
  console.log('文件上传成功:', response, file)
  operationForm.value.attachmentUrl = response.data || response.url || ''

  // 更新文件列表显示
  uploadedFiles.value = [
    {
      name: file.name,
      url: response.data || response.url || '',
      status: 'success'
    }
  ]

  ElMessage.success('文件上传成功')
}

function handleUploadError(error: any, file: any) {
  console.error('文件上传失败:', error, file)
  ElMessage.error('文件上传失败')
}

function handleUploadRemove(file: any) {
  console.log('删除文件:', file)
  uploadedFiles.value = []
  operationForm.value.attachmentUrl = ''
  ElMessage.success('文件已删除')
}

// 获取文件名
function getFileName(url: string) {
  if (!url) return ''
  return url.substring(url.lastIndexOf('/') + 1)
}

// 删除附件
function removeAttachment() {
  operationForm.value.attachmentUrl = ''
  uploadedFiles.value = []
  ElMessage.success('附件已删除')
}

// 预览附件
function previewAttachment() {
  if (operationForm.value.attachmentUrl) {
    window.open(operationForm.value.attachmentUrl, '_blank')
  }
}

async function submitOperation() {
  // 防连点：如果正在提交，直接返回
  if (operationSubmitting.value) {
    return
  }

  try {
    operationSubmitting.value = true
    console.log('提交操作:', operationType.value, operationForm.value)

    // 根据操作类型调用不同的API
    switch (operationType.value) {
      case 'buy-in':
        await createBuyIn({
          warehouseId: operationForm.value.warehouseId,
          weight: operationForm.value.weight,
          operationSubtype: operationForm.value.operationSubtype,
          creator: operationForm.value.creator,
          remark: operationForm.value.remark,
          attachmentUrl: operationForm.value.attachmentUrl
        })
        break
      case 'sales-return':
        await createSalesReturn({
          warehouseId: operationForm.value.warehouseId,
          weight: operationForm.value.weight,
          operationSubtype: operationForm.value.operationSubtype,
          creator: operationForm.value.creator,
          remark: operationForm.value.remark,
          attachmentUrl: operationForm.value.attachmentUrl
        })
        break
      case 'outbound':
        await createOutbound({
          warehouseId: operationForm.value.warehouseId,
          operationSubtype: operationForm.value.operationSubtype,
          weight: operationForm.value.weight,
          creator: operationForm.value.creator,
          remark: operationForm.value.remark,
          attachmentUrl: operationForm.value.attachmentUrl
        })
        break
      case 'transfer':
        if (!operationForm.value.toWarehouseId) {
          ElMessage.error('请选择调入仓库')
          return
        }
        await createTransfer({
          transferType: 1, // 调拨
          fromWarehouseId: operationForm.value.fromWarehouseId!,
          toWarehouseId: operationForm.value.toWarehouseId!,
          transferWeight: operationForm.value.transferWeight,
          transferReason: operationForm.value.transferReason,
          creator: operationForm.value.creator,
          remark: operationForm.value.remark,
          attachmentUrl: operationForm.value.attachmentUrl
        })
        break
      case 'dispatch':
        if (!operationForm.value.toWarehouseId) {
          ElMessage.error('请选择接收仓库')
          return
        }
        // 获取选中的接收仓库，从中提取teamWarehouseId
        const selectedWarehouse = warehouseList.value.find(
          (wh) => wh.id === operationForm.value.toWarehouseId
        )
        await createDispatch({
          transferType: 2, // 派发
          fromWarehouseId: operationForm.value.fromWarehouseId!,
          toWarehouseId: operationForm.value.toWarehouseId!,
          transferWeight: operationForm.value.dispatchWeight,
          transferReason: operationForm.value.dispatchReason,
          creator: operationForm.value.creator,
          remark: operationForm.value.remark,
          attachmentUrl: operationForm.value.attachmentUrl,
          teamWarehouseId:
            selectedWarehouse?.teamWarehouseId || currentWarehouse.value?.teamWarehouseId
        })
        break
      case 'return':
        if (!operationForm.value.fromWarehouseId) {
          ElMessage.error('未找到对应的还料出料仓')
          return
        }
        if (!operationForm.value.toWarehouseId) {
          ElMessage.error('请选择还料入料仓')
          return
        }
        await createReturn({
          fromWarehouseId: operationForm.value.toWarehouseId!, // 还料入料仓（当前仓库）
          toWarehouseId: operationForm.value.fromWarehouseId!, // 还料出料仓（个人仓）
          transferWeight: operationForm.value.returnWeight,
          transferReason: operationForm.value.returnReason,
          transferType: operationForm.value.transferType,
          creator: operationForm.value.creator,
          remark: operationForm.value.remark,
          attachmentUrl: operationForm.value.attachmentUrl
        })
        break
      default:
        ElMessage.error('未知操作类型')
        return
    }

    ElMessage.success('操作成功')
    operationDialogVisible.value = false

    // 重新加载数据
    await loadGlobalStats() // 重新加载全局统计数据
    if (activeTab.value === 'merchant') {
      await loadMerchant()
    } else {
      await loadSales()
    }
  } catch (error) {
    console.error('操作失败:', error)
    // 业务错误提示已由全局响应拦截器统一弹出，这里不再重复提示
  } finally {
    operationSubmitting.value = false
  }
}

function resetMerchant() {
  merchantQuery.pageNo = 1
  merchantQuery.pageSize = 10
  merchantQuery.name = ''
  merchantQuery.type = null
  merchantQuery.types = [1, 2] // 重置为公司仓和团队仓
  loadMerchant()
}

function resetSales() {
  salesQuery.pageNo = 1
  salesQuery.pageSize = 10
  salesQuery.name = ''
  salesQuery.type = null
  salesQuery.types = [3] // 重置为人员仓
  loadSales()
}

// 仓库详情相关方法
async function openWarehouseDetail(row: any) {
  console.log('=== 双击事件触发 ===')
  console.log('打开仓库详情:', row)
  console.log('row.id:', row?.id)

  try {
    selectedWarehouse.value = row
    recordQuery.warehouseId = row.id
    recordQuery.pageNo = 1
    recordQuery.pageSize = 10

    console.log('设置弹窗可见性为true')
    warehouseDetailVisible.value = true
    console.log('warehouseDetailVisible.value:', warehouseDetailVisible.value)

    // 加载操作记录和统计
    console.log('开始加载数据...')
    await Promise.all([loadRecordList(), loadRecordStats()])
    console.log('数据加载完成')
  } catch (error: any) {
    console.error('打开仓库详情时出错:', error)
    ElMessage.error('打开仓库详情失败: ' + (error?.message || '未知错误'))
  }
}

// 分页处理函数
// 商家户分页
const handleMerchantSizeChange = (size: number) => {
  console.log('商家户每页条数变化:', size)
  merchantQuery.pageSize = size
  merchantQuery.pageNo = 1 // 重置到第一页
  loadMerchant()
}

const handleMerchantCurrentChange = (page: number) => {
  console.log('商家户页码变化:', page)
  merchantQuery.pageNo = page
  loadMerchant()
}

// 销售户分页
const handleSalesSizeChange = (size: number) => {
  console.log('销售户每页条数变化:', size)
  salesQuery.pageSize = size
  salesQuery.pageNo = 1 // 重置到第一页
  loadSales()
}

const handleSalesCurrentChange = (page: number) => {
  console.log('销售户页码变化:', page)
  salesQuery.pageNo = page
  loadSales()
}

// 操作记录分页
const handleRecordSizeChange = (size: number) => {
  console.log('操作记录每页条数变化:', size)
  recordQuery.pageSize = size
  recordQuery.pageNo = 1 // 重置到第一页
  loadRecordList()
}

const handleRecordCurrentChange = (page: number) => {
  console.log('操作记录页码变化:', page)
  recordQuery.pageNo = page
  loadRecordList()
}

// 新增仓库相关函数
const openAddWarehouseDialog = async () => {
  // 重置表单
  Object.assign(warehouseForm, {
    code: '',
    name: '',
    type: 1,
    teamWarehouseId: undefined,
    userId: undefined,
    responsiblePerson: '', // 负责人名称
    responsiblePersonId: undefined, // 负责人ID
    status: 1
  })

  // 清空团队仓库列表
  teamWarehouseList.value = []

  addWarehouseDialogVisible.value = true
}

// 监听仓库类型变化，当选择人员仓时加载团队仓库列表
const onWarehouseTypeChange = async (type: number) => {
  console.log('仓库类型变化:', type)
  if (type === 3) {
    // 选择人员仓时，加载团队仓库列表
    console.log('开始加载团队仓库列表...')
    try {
      teamWarehouseList.value = await GoldWarehouseApi.getTeamWarehouses()
      console.log('加载团队仓库列表成功:', teamWarehouseList.value.length)
    } catch (error) {
      console.error('加载团队仓库列表失败:', error)
      ElMessage.error('加载团队仓库列表失败')
      teamWarehouseList.value = []
    }
  } else {
    // 选择其他类型时，清空团队仓库列表
    console.log('选择非人员仓，清空团队仓库列表')
    teamWarehouseList.value = []
    warehouseForm.teamWarehouseId = undefined
  }
}

// 负责人变更处理
const onResponsiblePersonChange = (userId: number | undefined) => {
  if (userId) {
    const user = userList.value.find((u) => u.id === userId)
    if (user) {
      warehouseForm.responsiblePerson = user.nickname || user.username
    }
  } else {
    warehouseForm.responsiblePerson = ''
  }
}

const submitWarehouse = async () => {
  if (!warehouseFormRef.value) return

  try {
    await warehouseFormRef.value.validate()
    warehouseSubmitting.value = true

    // 构建提交数据，只传必要字段
    const submitData: any = {
      code: warehouseForm.code,
      name: warehouseForm.name,
      type: warehouseForm.type,
      responsiblePerson: warehouseForm.responsiblePerson,
      status: warehouseForm.status
    }

    // 根据仓库类型添加对应的字段
    // 公司仓（type=1）：传 teamId 和 userId
    // 团队仓（type=2）：传 teamId 和 userId
    // 人员仓（type=3）：传 userId、teamId、teamWarehouseId

    // 统一处理 userId（负责人ID）
    if (warehouseForm.responsiblePersonId) {
      submitData.userId = warehouseForm.responsiblePersonId
    }

    // 统一处理 teamId 和 teamWarehouseId
    // 公司仓和团队仓需要传 teamId
    if (warehouseForm.type === 1 || warehouseForm.type === 2) {
      // TODO: teamId 应该从当前用户的上下文中获取
      // 如果后端需要根据当前登录用户自动填充，这里可以不传
      // 如果需要手动指定，可以通过查询接口获取团队列表让用户选择
      // submitData.teamId = ???  // 从用户上下文获取或用户选择
    }

    // 人员仓需要传 teamWarehouseId
    if (warehouseForm.type === 3 && warehouseForm.teamWarehouseId) {
      submitData.teamWarehouseId = warehouseForm.teamWarehouseId
    }

    console.log('提交仓库数据:', submitData)
    await createWarehouse(submitData)

    ElMessage.success('仓库创建成功')
    addWarehouseDialogVisible.value = false

    // 刷新商家户列表
    await loadMerchant()
  } catch (error) {
    console.error('创建仓库失败:', error)
    ElMessage.error('创建仓库失败')
  } finally {
    warehouseSubmitting.value = false
  }
}

async function loadRecordList() {
  if (!recordQuery.warehouseId) return

  recordLoading.value = true
  try {
    console.log('加载操作记录:', recordQuery)
    const result = (await getOperationRecordPage({
      pageNo: recordQuery.pageNo,
      pageSize: recordQuery.pageSize,
      warehouseId: recordQuery.warehouseId || undefined
    })) as any

    console.log('=== API响应完整数据 ===')
    console.log('result:', result)
    console.log('result.data:', result?.data)
    console.log('result.data.list:', result?.data?.list)
    console.log('result.data.total:', result?.data?.total)

    // 尝试多种数据路径
    let list: any[] = []
    let total = 0

    if (result) {
      if (result.data && result.data.list) {
        // 标准格式: result.data.list
        list = result.data.list
        total = result.data.total || 0
        console.log('使用标准格式解析数据')
      } else if (result.list) {
        // 直接格式: result.list
        list = result.list
        total = result.total || 0
        console.log('使用直接格式解析数据')
      } else if (Array.isArray(result)) {
        // 数组格式: result 本身就是数组
        list = result
        total = result.length
        console.log('使用数组格式解析数据')
      } else {
        console.log('无法识别的数据格式:', result)
      }
    }

    recordList.value = list
    recordTotal.value = total
    console.log('设置后的recordList.value:', recordList.value)
    console.log('设置后的recordTotal.value:', recordTotal.value)
    console.log('操作记录加载成功:', recordList.value.length, '条')
  } catch (error) {
    console.error('加载操作记录失败:', error)
    ElMessage.error('加载操作记录失败')
  } finally {
    recordLoading.value = false
  }
}

async function loadRecordStats() {
  if (!recordQuery.warehouseId) return

  try {
    console.log('加载操作统计:', recordQuery.warehouseId)
    const result = (await getOperationStats({ warehouseId: recordQuery.warehouseId })) as any

    console.log('=== 统计API响应完整数据 ===')
    console.log('result:', result)
    console.log('result.data:', result?.data)
    console.log('result.code:', result?.code)

    // 处理CommonResult响应格式
    let statsData: any = null
    if (result && result.data) {
      // CommonResult格式: { code: 0, data: { todayIn: ..., todayOut: ..., balance: ... } }
      statsData = result.data
    } else if (result && result.code === 0) {
      // 如果直接返回数据
      statsData = result
    } else if (result) {
      // 如果result本身就是数据
      statsData = result
    }

    console.log('解析后的statsData:', statsData)

    if (statsData) {
      recordStats.todayIn = statsData.todayIn || 0
      recordStats.todayOut = statsData.todayOut || 0
      recordStats.balance = statsData.balance || 0
      console.log('设置后的recordStats:', recordStats)
      console.log('操作统计加载成功:', recordStats)
    } else {
      console.log('统计API响应数据格式不正确:', result)
    }
  } catch (error) {
    console.error('加载操作统计失败:', error)
  }
}

// 操作记录相关辅助方法
function getRecordTagType(operationSubtype: number) {
  // 1-销售回料，2-买料入料，3-调拨入料，4-派发入料，5-收货给料，10-还料入料 (入料)
  // 6-调拨出料，7-派发出料，8-采购出料，9-还料出料 (出料)
  if ((operationSubtype >= 1 && operationSubtype <= 5) || operationSubtype === 10) {
    return 'success' // 入料 - 绿色
  } else if (operationSubtype >= 6 && operationSubtype <= 9) {
    return 'warning' // 出料 - 橙色
  }
  return 'info'
}

function getRecordTypeText(operationSubtype: number) {
  // 1-销售回料，2-买料入料，3-调拨入料，4-派发入料，5-收货给料，10-还料入料 (入料)
  // 6-调拨出料，7-派发出料，8-采购出料，9-还料出料 (出料)
  console.log(
    'getRecordTypeText - operationSubtype:',
    operationSubtype,
    'type:',
    typeof operationSubtype
  )
  if ((operationSubtype >= 1 && operationSubtype <= 5) || operationSubtype === 10) {
    return '入料'
  } else if (operationSubtype >= 6 && operationSubtype <= 9) {
    return '出料'
  }
  console.log('getRecordTypeText - 未知类型:', operationSubtype)
  return '未知'
}

function getRecordSubtypeText(operationSubtype: number) {
  const subtypeMap: { [key: number]: string } = {
    1: '销售回料',
    2: '买料入料',
    3: '调拨入料',
    4: '派发入料',
    5: '收货给料',
    6: '调拨出料',
    7: '派发出料',
    8: '采购出料',
    9: '还料出料',
    10: '还料入料'
  }
  console.log(
    'getRecordSubtypeText - operationSubtype:',
    operationSubtype,
    'result:',
    subtypeMap[operationSubtype]
  )
  return subtypeMap[operationSubtype] || '未知类型'
}

function getWeightClass(weight: number, operationType: number) {
  if (!weight && weight !== 0) return 'weight-zero'
  if (operationType === 1) return 'weight-positive' // 入料 - 绿色
  if (operationType === 2) return 'weight-negative' // 出料 - 红色
  return 'weight-zero'
}

function getFormattedWeight(weight: number, operationType: number) {
  if (!weight && weight !== 0) return '0.000克'

  const formattedWeight = weight.toFixed(3)
  if (operationType === 1) {
    // 入料显示正号
    return `+${formattedWeight}克`
  } else if (operationType === 2) {
    // 出料显示负号
    return `-${formattedWeight}克`
  }
  return `${formattedWeight}克`
}

// 加载用户列表
const loadUserList = async () => {
  try {
    userList.value = await getSimpleUserList()
    console.log('加载用户列表成功，共', userList.value.length, '个用户')
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  }
}

onMounted(async () => {
  console.log('页面挂载，开始加载数据...')
  await loadGlobalStats() // 加载全局统计
  await loadMerchant()
  await loadUserList() // 加载用户列表

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    isMobile.value = window.innerWidth <= 768
  })
})

// 订单选择相关函数
async function openOrderSelection(type: 'purchase' | 'sales') {
  orderSelectionType.value = type
  orderSelectionDialogVisible.value = true
  resetOrderQuery()

  // 加载产品列表
  try {
    productList.value = await ProductApi.getProductSimpleList()
  } catch (error) {
    console.error('加载产品列表失败:', error)
    ElMessage.error('加载产品列表失败')
  }

  searchOrders()
}

function resetOrderQuery() {
  orderQuery.value = {
    orderNo: '',
    product: '',
    startDate: '',
    endDate: '',
    pageNo: 1,
    pageSize: 10
  }
}

async function searchOrders() {
  orderLoading.value = true
  try {
    // 构建查询参数
    const queryParams: any = {
      pageNo: orderQuery.value.pageNo,
      pageSize: orderQuery.value.pageSize,
      no: orderQuery.value.orderNo || undefined,
      productId: orderQuery.value.product || undefined,
      orderTime:
        orderQuery.value.startDate && orderQuery.value.endDate
          ? [orderQuery.value.startDate, orderQuery.value.endDate]
          : undefined
    }

    let data
    if (orderSelectionType.value === 'purchase') {
      // 查询采购订单（仅展示可入库）
      queryParams.inEnable = true
      data = await PurchaseOrderApi.getPurchaseOrderPage(queryParams)
    } else {
      // 查询销售订单（仅展示可出库）
      queryParams.outEnable = true
      data = await SaleOrderApi.getSaleOrderPage(queryParams)
    }

    // 转换数据格式以适配表格显示
    orderList.value = data.list.map((order: any) => ({
      id: order.id,
      orderNo: order.no,
      supplier: order.supplierName || order.supplier?.name,
      customer: order.customerName || order.customer?.name,
      productInfo: order.items?.[0]?.productName || '黄金1号', // 取第一个产品的名称
      orderTime: order.orderTime ? new Date(order.orderTime).toISOString().split('T')[0] : '',
      creator: order.creator || '系统',
      totalQuantity: order.totalCount || 0,
      inboundQuantity: order.inCount || 0,
      outboundQuantity: order.outCount || 0,
      totalAmount: order.totalPrice || 0,
      taxAmount: order.totalPrice * 0.1 || 0 // 假设税率10%
    }))

    orderTotal.value = data.total
  } catch (error) {
    console.error('搜索订单失败:', error)
    ElMessage.error('搜索订单失败')
    orderList.value = []
    orderTotal.value = 0
  } finally {
    orderLoading.value = false
  }
}

function handleOrderSelection(selection: any[]) {
  selectedOrder.value = selection.length > 0 ? selection[0] : null
}

function confirmOrderSelection() {
  if (!selectedOrder.value) {
    ElMessage.warning('请选择一个订单')
    return
  }

  operationForm.value.relatedOrderNo = selectedOrder.value.orderNo
  operationForm.value.relatedOrderId = selectedOrder.value.id
  orderSelectionDialogVisible.value = false

  ElMessage.success('订单选择成功')
}

function handleOrderSizeChange(size: number) {
  orderQuery.value.pageSize = size
  orderQuery.value.pageNo = 1
  searchOrders()
}

function handleOrderCurrentChange(page: number) {
  orderQuery.value.pageNo = page
  searchOrders()
}
</script>

<style scoped>
.app-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.header h1 {
  margin: 0;
  font-size: 20px;
}
.main-content {
  padding: 16px;
  max-width: 1400px;
  margin: 0 auto;
}
/* 统计卡片样式 - 已注释，如需恢复请取消注释 */
/*
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 16px;
}
.stat-card {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  text-align: center;
}
.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #409eff;
}
.stat-label {
  color: #666;
  margin-top: 4px;
}
*/
.search-form {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 12px;
}
.operation-buttons-vertical {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.balance-high {
  color: #67c23a;
  font-weight: bold;
}
.balance-medium {
  color: #e6a23c;
  font-weight: bold;
}
.balance-low {
  color: #f56c6c;
  font-weight: bold;
}

/* 仓库详情弹窗样式 */
.warehouse-detail {
  padding: 20px;
}

.warehouse-info {
  margin-bottom: 24px;
}

.warehouse-info h3 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
  min-width: 80px;
}

.info-item .value {
  color: #303133;
  font-weight: 500;
}

.record-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.record-stats .stat-card {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  text-align: center;
  border: 1px solid #ebeef5;
}

.record-stats .stat-number {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 8px;
}

.record-stats .stat-number.green {
  color: #67c23a;
}

.record-stats .stat-number.red {
  color: #f56c6c;
}

.record-stats .stat-label {
  color: #909399;
  font-size: 14px;
}

.record-list h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.records-container {
  max-height: 500px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background: #fff;
}

.record-item {
  border-bottom: 1px solid #ebeef5;
  padding: 16px;
  transition: background-color 0.2s;
}

.record-item:last-child {
  border-bottom: none;
}

.record-item:hover {
  background-color: #f8f9fa;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.record-operator {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
  min-width: 80px;
  text-align: right;
}

.record-time {
  color: #909399;
  font-size: 14px;
}

.record-operator {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.record-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.record-left {
  flex: 1;
}

.record-type {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.record-subtype {
  margin-left: 8px;
  color: #606266;
  font-size: 14px;
}

.record-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.detail-label {
  color: #909399;
  font-size: 13px;
  margin-right: 8px;
  min-width: 80px;
  text-align: right;
  flex-shrink: 0;
}

.detail-value {
  color: #303133;
  font-size: 13px;
  font-weight: 500;
}

.detail-link {
  color: #409eff;
  text-decoration: none;
  font-size: 13px;
}

.detail-link:hover {
  text-decoration: underline;
}

.attachment-link,
.attachment-empty {
  display: inline-block;
  min-width: 60px;
  text-align: left;
}

.weight-positive {
  color: #67c23a;
  font-weight: 600;
}

.weight-negative {
  color: #f56c6c;
  font-weight: 600;
}

.weight-zero {
  color: #909399;
}

.empty-state {
  padding: 40px;
  text-align: center;
}

.record-pagination {
  margin-top: 16px;
  text-align: center;
}

/* 附件预览样式 */
.attachment-preview {
  margin-top: 12px;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  gap: 8px;
}

.attachment-icon {
  color: #409eff;
  font-size: 16px;
}

.attachment-name {
  flex: 1;
  color: #606266;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 操作按钮样式 */
.operation-buttons-vertical {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.operation-buttons-vertical .el-button {
  width: 100%;
  margin: 0;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .app-container {
    padding: 0;
    min-height: 100vh;
  }

  .header {
    padding: 6px 10px;
    text-align: center;
    margin-bottom: 4px;
  }

  .header h1 {
    font-size: 14px;
    margin: 0;
    font-weight: bold;
  }

  .header p {
    display: none;
  }

  .el-card {
    margin: 0;
    border-radius: 0;
  }

  .main-content {
    padding: 0;
  }

  /* 统计卡片移动端样式 - 已注释，如需恢复请取消注释 */
  /*
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
    margin-bottom: 16px;
  }

  .stat-card {
    padding: 12px 8px;
  }

  .stat-number {
    font-size: 18px;
  }

  .stat-label {
    font-size: 11px;
  }
  */

  .search-form {
    padding: 4px 8px;
    background: #fff;
    margin-bottom: 4px;
  }

  .search-form .el-form {
    flex-direction: column;
    gap: 0;
  }

  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 4px;
    width: 100%;
  }

  .search-form .el-form-item__label {
    font-size: 11px;
    font-weight: 500;
    width: 100% !important;
    text-align: left;
    margin-bottom: 2px;
  }

  .search-form .el-input,
  .search-form .el-select {
    width: 100% !important;
    font-size: 12px;
    height: 28px;
  }

  .search-form .el-input__wrapper,
  .search-form .el-select .el-input__wrapper {
    border-radius: 3px;
  }

  .search-form .el-button {
    width: 100%;
    margin-right: 0;
    margin-bottom: 3px;
    height: 28px;
    font-size: 12px;
    border-radius: 3px;
  }

  /* 表格移动端适配 */
  .el-table {
    font-size: 10px;
    border-radius: 0;
  }

  .el-table .el-table__header th {
    padding: 2px 1px;
    font-size: 10px;
    font-weight: 600;
    background: #f5f7fa;
    line-height: 1.1;
  }

  .el-table .el-table__body td {
    padding: 2px 1px;
    font-size: 10px;
    line-height: 1.2;
  }

  /* 减小表格行高 */
  .el-table .el-table__body tr {
    height: auto;
  }

  .el-table .el-table__body td .cell {
    padding: 1px 0;
    line-height: 1.2;
  }

  .el-table .el-button {
    padding: 2px 4px;
    font-size: 9px;
    margin: 0;
    border-radius: 2px;
    line-height: 1.1;
    height: auto;
  }

  .el-table .el-button + .el-button {
    margin-left: 0;
  }

  /* 表格在移动端支持横向滚动 */
  .el-table__body-wrapper {
    overflow-x: auto;
  }

  .el-table .cell {
    word-break: break-word;
    line-height: 1.4;
  }

  /* 操作时间列在移动端更窄 */
  .operation-time-column .cell {
    font-size: 8px;
    padding: 1px 2px;
  }

  /* 操作列固定在右侧 */
  .el-table__fixed-right {
    box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  }

  /* 操作按钮在移动端更紧凑 */
  .el-table__fixed-right .operation-buttons-vertical {
    padding: 0 4px;
  }

  /* 操作按钮组移动端适配 */
  .operation-buttons-vertical {
    display: flex;
    flex-direction: column;
    gap: 1px;
  }

  .operation-buttons-vertical .el-button {
    width: 100%;
    font-size: 9px;
    padding: 2px 4px;
    height: auto;
    min-height: 20px;
  }

  /* 弹窗移动端适配 */
  .el-dialog {
    width: 100% !important;
    max-width: 100% !important;
    margin: 0 !important;
    border-radius: 0 !important;
    height: 100vh !important;
    margin-top: 0 !important;
    margin-bottom: 0 !important;
  }

  .el-dialog__header {
    padding: 6px 10px;
    font-size: 13px;
    border-bottom: 1px solid #eee;
  }

  .el-dialog__body {
    padding: 4px 8px;
    max-height: calc(100vh - 50px);
    overflow-y: auto;
  }

  .el-dialog__footer {
    padding: 3px 8px;
    border-top: 1px solid #eee;
  }

  .el-dialog__footer .el-button {
    width: 100%;
    height: 28px;
    font-size: 10px;
    margin-bottom: 2px;
  }

  .el-form-item__label {
    font-size: 10px;
    font-weight: 500;
    margin-bottom: 2px;
    color: #333;
    width: 60px !important;
    line-height: 1.1;
  }

  .el-form-item__content {
    margin-left: 60px !important;
  }

  .el-form-item {
    margin-bottom: 3px;
  }

  /* 确保附件字段有足够的上边距 */
  .el-form-item:has(.el-upload) {
    margin-top: 6px;
    margin-bottom: 6px;
  }

  .el-input,
  .el-select,
  .el-textarea,
  .el-input-number {
    font-size: 11px;
    height: 28px;
  }

  .el-input-number .el-input__wrapper {
    padding: 0 3px;
  }

  .el-textarea .el-textarea__inner {
    font-size: 11px;
    min-height: 35px;
  }

  /* 备注字段增加下边距，避免与附件重叠 */
  .el-form-item:has(.el-textarea) {
    margin-bottom: 6px;
  }

  .el-radio-group .el-radio {
    font-size: 11px;
    margin-bottom: 3px;
  }

  /* 附件上传区域移动端优化 */
  .el-upload {
    width: 100%;
  }

  .el-upload-dragger {
    width: 100%;
    padding: 1px 2px;
    height: 30px;
    min-height: 30px;
  }

  .el-upload-dragger__icon {
    font-size: 10px;
    margin: 0;
  }

  .el-upload-dragger__text {
    font-size: 7px;
    line-height: 1;
  }

  .el-upload__tip {
    font-size: 6px;
    margin-top: 1px;
    line-height: 1;
  }

  /* 分页容器移动端适配 */
  .pagination-container {
    padding: 4px;
  }

  /* 分页移动端适配 */
  .el-pagination {
    justify-content: center;
  }

  .el-pagination .el-pagination__sizes,
  .el-pagination .el-pagination__total {
    display: none;
  }

  .el-pagination .btn-prev,
  .el-pagination .btn-next {
    padding: 0 8px;
    font-size: 12px;
  }

  .el-pagination .el-pager li {
    min-width: 28px;
    height: 28px;
    line-height: 28px;
    font-size: 12px;
  }

  /* Tabs移动端优化 */
  .el-tabs__header {
    margin: 0;
    padding: 0 8px;
  }

  .el-tabs__item {
    font-size: 12px;
    padding: 6px 10px;
    height: auto;
  }

  .el-tabs__nav {
    background: #fff;
  }

  .el-tabs__active-bar {
    height: 2px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 480px) {
  .header {
    padding: 6px 10px;
  }

  .header h1 {
    font-size: 14px;
  }

  .search-form {
    padding: 4px 8px;
  }

  .search-form .el-form-item {
    margin-bottom: 4px;
  }

  .search-form .el-form-item__label {
    font-size: 11px;
    margin-bottom: 2px;
  }

  .search-form .el-input,
  .search-form .el-select {
    height: 28px;
    font-size: 12px;
  }

  .search-form .el-button {
    height: 28px;
    font-size: 12px;
    margin-bottom: 3px;
  }

  .el-tabs__item {
    font-size: 12px;
    padding: 6px 10px;
  }

  .el-table {
    font-size: 10px;
  }

  .el-table .el-table__header th {
    padding: 3px 2px;
    font-size: 10px;
    line-height: 1.2;
  }

  .el-table .el-table__body td {
    padding: 3px 2px;
    font-size: 10px;
    line-height: 1.2;
  }

  .el-table .el-table__body td .cell {
    padding: 1px 0;
    line-height: 1.2;
  }

  .el-table .el-button {
    padding: 2px 4px;
    font-size: 9px;
    min-height: 20px;
  }

  .operation-buttons-vertical .el-button {
    padding: 2px 4px;
    font-size: 9px;
    min-height: 20px;
  }

  .pagination-container {
    padding: 6px;
  }

  .el-pagination {
    justify-content: center;
  }

  .el-pagination .el-pager li {
    min-width: 24px;
    height: 24px;
    line-height: 24px;
    font-size: 11px;
  }
}

/* 分页容器样式 */
.pagination-container {
  padding: 16px;
  text-align: center;
}

/* 筛选折叠头部样式 */
.search-form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  cursor: pointer;
  user-select: none;
  font-weight: 500;
  color: #303133;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 12px;
}

.search-form-header:hover {
  color: #409eff;
}

.search-toggle-icon {
  transition: transform 0.3s;
  font-size: 16px;
  color: #909399;
}

.search-toggle-icon.is-collapsed {
  transform: rotate(0deg);
}

.search-form-header:hover .search-toggle-icon {
  color: #409eff;
}

/* 移动端筛选头部样式 */
@media (max-width: 768px) {
  .search-form-header {
    padding: 4px 0;
    margin-bottom: 4px;
    font-size: 12px;
  }

  .search-toggle-icon {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .search-form-header {
    padding: 4px 0;
    margin-bottom: 6px;
    font-size: 13px;
  }

  .search-toggle-icon {
    font-size: 13px;
  }
}
</style>
